"""
实现狼管理器
创建者：Carburn Ashroom
2024.1.18
"""

from random import randint

import char
import config
from PySide6.QtCore import QPoint, QRectF, QSizeF
from PySide6.QtGui import QPainter, QPixmap


class WolfCreator:
    """WolfCreator类是一个全局狼管理器"""
    def __init__(self, scrn, spawn_spd=config.WOLF_SPAN, wolf_img=config.WOLF_DIR, width=config.WOLF_WIDTH):
        self.wolves = []
        self.spawn_pos = None
        self.img = QPixmap(wolf_img)
        self.width = width
        self.height = width * self.img.height() / self.img.width()
        self.interval = spawn_spd
        self.spawn_proc = 0
        self.screen = scrn
        
        self.rand_pos()

    def rand_pos(self):
        """随机生成点的坐标"""
        x = randint(0, int(self.screen.width-self.width))
        y = randint(0, int(self.screen.height-self.height))
        self.spawn_pos = QPoint(x, y)

    def draw(self, dest):
        """绘制"""
        pa = QPainter(dest)
        proc = self.spawn_proc / self.interval
        dest_rect = QRectF(self.spawn_pos, QSizeF(self.width, self.height*proc))
        pa.drawPixmap(dest_rect, self.img, QRectF(0, 0, self.img.width(), self.img.height()*proc))
        pa.end()
        for w in self.wolves:
            w.draw(dest)

    def update(self, sheep):
        """更新每一帧"""
        for w in self.wolves:
            if w.update(sheep):
                return True
        self.spawn_proc += 1
        if self.spawn_proc == self.interval:
            self.wolves.append(char.Wolf(self.spawn_pos, self.screen))
            self.spawn_proc = 0
            self.rand_pos()
